// 文字换行
const textWrap = (str, firstNum, twoNum) => {
    const len = str.length
    let strStart = str
    let strEnd = ''

    if (len > firstNum) {
        strStart = str.substring(0, firstNum)
        const stl = str.substring(firstNum, len)
        if (stl.length > twoNum) {
            strEnd = '...'.padStart(twoNum - 1, stl)
        } else {
            strEnd = stl
        }
    }
    return {
        strStart,
        strEnd
    }
}

const setShareImg = (options) => {
    const {id, goodsimg, qrcode, autoimg, goodsname, goodsmoney, goodstype, type, userimg, username} = options
    const ctx = wx.createCanvasContext(id)
    // 设置背景为白色
    ctx.setFillStyle('#fff')
    ctx.fillRect(0, 0, 750, 1400)
    // 生成商品图片
    ctx.drawImage(goodsimg, 0, 0, 750, 750)
    ctx.setFontSize(34)
    // 生成标题
    ctx.fillStyle = '#000'

    const goodsTitle = textWrap(goodsname, 19, 14)
    // let textW = ctx.measureText(str).width / 4  // 设置文字居中
    ctx.fillText(goodsTitle.strStart, 50, 820)
    ctx.fillText(goodsTitle.strEnd, 50, 870)
    // 生成价格
    ctx.setFontSize(30)
    ctx.fillStyle = '#f65f26'
    ctx.fillText('￥', 50, 1010)
    ctx.setFontSize(50)
    ctx.fillText(goodsmoney.split('￥')[1], 80, 1010)
    // 生成规格
    ctx.setFontSize(30)
    ctx.fillStyle = '#707070'
    // ctx.fillText(goodstype, 420, 860)
    // 广告语
    ctx.setFontSize(28)
    const bannerStr = '来康  一种健康的生活方式'
    ctx.fillText(bannerStr, 50, 1100)
    // 生成二维码
    ctx.drawImage(qrcode, 470, 870, 250, 250)
    // 遮盖二维码底部文字
    // ctx.setFillStyle('#fff')
    // ctx.fillRect(488, 1105, 350, 60)
    // 绘制新的文字
    ctx.fillStyle = '#626262'
    ctx.setFontSize(20)
    // ctx.fillText('长按二维码进入小程序', 493, 1130)

    if (type === 'user') {
        ctx.setFontSize(35)
        ctx.drawImage(userimg, 50, 1160, 100, 100)
        const text = textWrap('正在参加集赞送礼，帮我点赞免费领礼品', 15, 15)
        ctx.fillText(`我是${username}`, 170, 1190)
        ctx.fillText(text.strStart, 170, 1240)
        ctx.fillText(text.strEnd, 170, 1280)
    } else {
        // 写入自定义图片 自定义图片大小 350 * 217
        // ctx.drawImage(autoimg, 320, 906, 350, 217)
        const imgurl = '/static/detail/share-img-bottom.jpg'
        ctx.drawImage(imgurl, 50, 1150, 650, 160)
    }
    return new Promise((resolve, rejcet) => {
        ctx.draw(true, () => {
            wx.canvasToTempFilePath({
                width: 750,
                heght: 1400,
                destWidth: 750,
                destHeight: 1400,
                canvasId: id,
                fileType: 'jpg',
                quality: 1,
                success: (res) => {
                    resolve({
                        img: res.tempFilePath
                    })
                },
                fail: (e) => {
                    console.error('draw方法生成图片错误', e)
                    rejcet(e)
                },
            })
        })
    })
}

const init = (id, options = {}) => {
    console.log(options)
    let {
        qrUrl,          // 小程序码地址
        goodsimg,       // 商品图片
        autoimg,        // 自定义图片
        goodsname,      // 商品名称
        goodsmoney,     // 商品金额
        goodstype,      // 小商品规格
        userimg,        // 用户头像，与type = user  一起使用
        type,           // null  user
        username,       // 用户昵称，与type = user  一起使用
    } = options

    // 缓存网络图片到本地
    let promise1 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
            src: goodsimg,
            success: function (res) {
                // console.log(res)
                resolve(res);
            },
            fail: e => {
                console.error('缓存商品首图出现错误', e)
                reject(e)
            }
        })
    })
    let promise2 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
            src: qrUrl,
            success: function (res) {
                // console.log(res)
                resolve(res);
            },
            fail: e => {
                console.error('缓存小程序码图片出现错误', e)
                reject(e)
            }
        })
    })

    // 用于判断是否来自点赞
    if (options.userimg) {
        let promise3 = new Promise(function (resolve, reject) {
            wx.getImageInfo({
                src: userimg,
                success: function (res) {
                    // console.log(res)
                    resolve(res)
                },
                fail: e => {
                    console.error('缓存用户头像出现错误', e)
                    reject(e)
                }
            })
        })
        let promiseAll = [promise1, promise2, promise3]
        return new Promise((reslove, reject) => {
            Promise.all(promiseAll).then(res => {
                let options = {
                    id,
                    goodsimg: res[0].path,
                    qrcode: res[1].path,
                    goodsname,
                    goodsmoney,
                    goodstype,
                    type,
                    userimg: res[2].path,
                    username
                }
                setShareImg(options).then(res => {
                    reslove(res)
                }).catch(e => {
                    reject(e)
                })
            }).catch(e => {
                console.error(e)
                reject(e)
            })
        })
    } else {
        return new Promise((reslove, reject) => {
            let promiseAll = [promise1, promise2]
            Promise.all(promiseAll).then(res => {
                let options = {
                    id,
                    goodsimg: res[0].path,
                    qrcode: res[1].path,
                    goodsname,
                    goodsmoney,
                    goodstype,
                    type
                }
                setShareImg(options).then(res => {
                    reslove(res)
                }).catch(e => {
                    reject(e)
                })
            }).catch(e => {
                console.error(e)
                reject(e)
            })
        })
    }


}

export default init
